package com.zzh.takeoutapp.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.activity.ClassifyActivity;
import com.zzh.takeoutapp.activity.HomeDiscountActivity;
import com.zzh.takeoutapp.activity.MoreActivity;
import com.zzh.takeoutapp.entity.HomeShopEntity;
import com.zzh.takeoutapp.model.HomeBean;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.view.DiscountsView;
import com.zzh.takeoutapp.view.FilterView;
import com.zzh.takeoutapp.view.HeaderBannerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 *
 */
public class HomeFragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
    /**
     * 头布局总数
     */
    private Activity context;
    private LayoutInflater inflater;
    private int TYPE_TOP0 = 0;
    private int TYPE_TOP1 = 1;
    private int TYPE_TOP2 = 2;
    private int TYPE_TOP3 = 3;
    private int TYPE_TOP4 = 4;
    private int ITEM_TYPE_BOTTOM = 5;
    private int TYPE_REFRESH = 6;
    private int count = 5;
    private List<HomeBean.DataBean.BannerBean> bannerList = new ArrayList<>(); // 广告数据
    private List<HomeBean.DataBean.CateAdvBean> cateAdvBeans = new ArrayList<>(); // 分类数据
    private List<HomeBean.DataBean.AdvBean> advBeans = new ArrayList<>();
    private HeaderBannerView bannerView;
    private int mBottomCount = 1;//底部View个数
    private HomeBean homeBeans;

    public List<HomeShopEntity.DataBean.ItemsBean> getNormalGoodsTitls() {
        return normalGoodsTitls;
    }

    public void setNormalGoodsTitls(List<HomeShopEntity.DataBean.ItemsBean> normalGoodsTitls) {
        this.normalGoodsTitls = normalGoodsTitls;
    }

    /**
     * 普通商品的（normalHolder）的标题集合,调用者传入
     */
    private List<HomeShopEntity.DataBean.ItemsBean> normalGoodsTitls;

    public HomeBean getHomeBeans() {
        return homeBeans;
    }

    public void setHomeBeans(HomeBean homeBeans) {
        this.homeBeans = homeBeans;
    }

    //判断当前item是否是FooterView
    public boolean isBottomView(int position) {
        return mBottomCount != 0 && position >= (count + (normalGoodsTitls != null ? normalGoodsTitls.size() : 0));
    }

    private TextHolder textHolder;
    private NormalSort normalSort;

    public TextHolder getTextHolder() {
        return textHolder;
    }

    public void setTextHolder(TextHolder textHolder) {
        this.textHolder = textHolder;
    }

    public HomeFragmentAdapter(Activity mContext) {
        this.context = mContext;
        this.inflater = LayoutInflater.from(context);
    }

    public void insert(List<HomeShopEntity.DataBean.ItemsBean> person, int position) {
        normalGoodsTitls.addAll(position - count, person);
        notifyItemInserted(position - count);
    }

    public HomeShopEntity.DataBean.ItemsBean getItem(int position) {
        if (position < normalGoodsTitls.size())
            return normalGoodsTitls.get(position);
        else
            return null;
    }

    public void startBanner() {
        if (bannerView != null)
            bannerView.enqueueBannerLoopMessage();
    }

    public void stopBanner() {
        if (bannerView != null)
            bannerView.removeBannerLoopMessage();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup arg0, int viewType) {
        View view = inflater.inflate(R.layout.item_home_order, arg0, false);
        View view_discounts = inflater.inflate(R.layout.include_text_discounts, arg0, false);
        if (homeBeans != null) {
            this.bannerList = homeBeans.getData().getBanner();
            this.advBeans = homeBeans.getData().getAdv();
            this.cateAdvBeans = homeBeans.getData().getCate_adv();
        }
        if (viewType == TYPE_TOP0) {//循环的bana
            bannerView = new HeaderBannerView(context);
            return new TypetypeHolder(bannerView.getView(bannerList));
        } else if (viewType == TYPE_TOP1) {
            View views = inflater.inflate(R.layout.activity, arg0, false);
            return new TypetypeHolders(views);
        } else if (viewType == TYPE_TOP2) {
            View views = inflater.inflate(R.layout.rv_item_normal, arg0, false);
            return new Normal(views);
        } else if (viewType == TYPE_TOP3) {
            View views = inflater.inflate(R.layout.include_text_view, arg0, false);
            normalSort = new NormalSort(views);
            return normalSort;
        } else if (viewType == TYPE_TOP4) {
            textHolder = new TextHolder(view_discounts);
            return textHolder;
        } else if (viewType == TYPE_REFRESH) {
            return new MyViewHolder(view);
        } else {
            View views = inflater.inflate(R.layout.item_user_adapter, arg0, false);
            int intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(intw, inth);
            view_discounts.measure(intw, inth);
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int height = wm.getDefaultDisplay().getHeight();
            ViewGroup.LayoutParams lp = views.getLayoutParams();
            lp.height = height;
            if (normalGoodsTitls != null && normalGoodsTitls.size() < 5) {
                int view_height = height - view.getMeasuredHeight() * (normalGoodsTitls.size() + 1) - view_discounts.getMeasuredHeight();
                ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, view_height);
                views.setLayoutParams(layoutParams);
            }
            return new BottomViewHolder(views);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_TOP0;
        } else if (position == 1) {
            return TYPE_TOP1;
        } else if (position == 2) {
            return TYPE_TOP2;
        } else if (position == 3) {
            return TYPE_TOP3;
        } else if (position == 4) {
            return TYPE_TOP4;
        } else if (mBottomCount != 0 && position >= (count + (normalGoodsTitls != null ? normalGoodsTitls.size() : 0))) {
            return ITEM_TYPE_BOTTOM;
        } else {
            return TYPE_REFRESH;
        }
    }

    private static String getValue(Map<Integer, String> map) {
        String value = "";
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            value = (String) entry.getValue();
        }
        return value;
    }

    private static Integer getKey(Map<Integer, String> map) {
        Integer value = 0;
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            value = (Integer) entry.getKey();
        }
        return value;
    }

    private void initCenterBean(TypetypeHolders holder) {
        holder.rvtype.setLayoutManager(new StaggeredGridLayoutManager(5,
                StaggeredGridLayoutManager.VERTICAL));
        TypeHistoryAdapter centerAdapter = new TypeHistoryAdapter(context, cateAdvBeans);
        holder.rvtype.setAdapter(centerAdapter);
        centerAdapter.setmOnItemClickLitener(new TypeHistoryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int postion) {
                if (postion == 9) {
                    Intent intent = new Intent(context, MoreActivity.class);
                    intent.putExtra("ClassifyValue", cateAdvBeans.get(postion).getTitle());
                    intent.putExtra("cate_id", cateAdvBeans.get(postion).getCate_id());
                    context.startActivity(intent);
                } else {
                    Intent intent = new Intent(context, ClassifyActivity.class);
                    intent.putExtra("ClassifyValue", cateAdvBeans.get(postion).getTitle());
                    intent.putExtra("cate_id", cateAdvBeans.get(postion).getCate_id());
                    context.startActivity(intent);
                }
            }

            @Override
            public void onItemLongClick(View v, int postion) {
            }
        });

    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof TypetypeHolders && cateAdvBeans.size() != 0) {
            initCenterBean(((TypetypeHolders) holder));//加载中间head下面的数据源
        } else if (holder instanceof Normal) {
            ImageManager.loadUrlImage(context, advBeans.get(0).getThumb(), ((Normal) holder).home_discount);
            ImageManager.loadUrlImage(context, advBeans.get(1).getThumb(), ((Normal) holder).home_special_offer);
            ((Normal) holder).home_discount.setOnClickListener(this);
            ((Normal) holder).home_special_offer.setOnClickListener(this);
        } else if (holder instanceof TextHolder) {
            ((TextHolder) holder).real_filterView.setOnDiscountClickListener(new DiscountsView.
                    OnDiscountClickListener() {
                @Override
                public void onDiscountClick(int position) {
                    textSortOnClickListener.onSortClick(((TextHolder) holder).real_filterView, position, false);
                }
            });
        } else if (holder instanceof NormalSort) {
            ((NormalSort) holder).filterView.setOnFilterClickListener(new FilterView.OnFilterClickListener() {
                @Override
                public void onFilterClick(int position) {
                    textSortOnClickListener.onSortClick(((NormalSort) holder).filterView, position);
                }
            });
        } else if (holder instanceof MyViewHolder) {
            if (normalGoodsTitls != null && normalGoodsTitls.size() > 0) {
                HomeShopEntity.DataBean.ItemsBean itemsBean = normalGoodsTitls.get(position - count);
                if (mOnItemClickLitener != null && position - count >= 0) {
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mOnItemClickLitener.onItemClick(holder.itemView, position - count);
                        }
                    });
                    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            mOnItemClickLitener.onItemLongClick(holder.itemView, position - count);
                            return true;
                        }
                    });
                }
                ImageManager.loadUrlImage(context, itemsBean.getWaimai().getLogo(), ((MyViewHolder) holder).draw_goods);
                ((MyViewHolder) holder).title.setText(itemsBean.getWaimai().getTitle());
                ((MyViewHolder) holder).tv_avg_score.setText(String.valueOf(itemsBean.getWaimai().getAvg_score()));
                ((MyViewHolder) holder).tv_orders.setText("月售  " + String.valueOf(itemsBean.getWaimai().getOrders()));
                ((MyViewHolder) holder).tv_juli_label.setText("30分钟 | " + String.valueOf(itemsBean.getWaimai().getJuli_label()));
                ((MyViewHolder) holder).min_amount.setText
                        ("起送  ￥" + String.valueOf(itemsBean.getWaimai().getMin_amount()) + "  |  " +
                                "配送  ￥" + String.valueOf(itemsBean.getWaimai().getFreight()) + "  |  " +
                                "人均  ￥" + String.valueOf(itemsBean.getWaimai().getFreight()));
                ((MyViewHolder) holder).rb.setRating(Float.parseFloat(itemsBean.getWaimai().getAvg_score()));
                List<HomeShopEntity.DataBean.ItemsBean.WaimaiBean.HuodongBean>
                        products = itemsBean.getWaimai().getHuodong();
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                        , LinearLayout.LayoutParams.WRAP_CONTENT);
                ((MyViewHolder) holder).linearLayout.setLayoutParams(params);
                ((MyViewHolder) holder).linearLayout.removeAllViews();
                for (int i = 0; i < products.size(); i++) {
                    LinearLayout linearLayout = (LinearLayout) View.inflate(context, R.layout.item_home_order_text, null);
                    TextView textView = linearLayout.findViewById(R.id.home_tag);
                    textView.setText(products.get(i).getTitle());
                    ((MyViewHolder) holder).linearLayout.addView(linearLayout);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_adv:
                context.startActivity(new Intent(context, HomeDiscountActivity.class));
                break;
            case R.id.home_special_offer:
                context.startActivity(new Intent(context, HomeDiscountActivity.class));
                break;
        }
    }

    //底部 ViewHolder
    public class BottomViewHolder extends RecyclerView.ViewHolder {
        public BottomViewHolder(View itemView) {
            super(itemView);
        }
    }

    //za折扣
    public class Normal extends RecyclerView.ViewHolder {
        @Bind(R.id.home_special_offer)
        ImageView home_special_offer;
        @Bind(R.id.iv_adv)
        ImageView home_discount;

        public Normal(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public NormalSort getNormalSort() {
        return normalSort;
    }

    public void setNormalSort(NormalSort normalSort) {
        this.normalSort = normalSort;
    }

    public class NormalSort extends RecyclerView.ViewHolder {
        @Bind(R.id.filter_view)
        FilterView filterView;

        public FilterView getFilterView() {
            return filterView;
        }

        public void setFilterView(FilterView filterView) {
            this.filterView = filterView;
        }

        public NormalSort(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class TextHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.discounts_view)
        DiscountsView real_filterView;

        public DiscountsView getReal_filterView() {
            return real_filterView;
        }

        public void setReal_filterView(DiscountsView real_filterView) {
            this.real_filterView = real_filterView;
        }

        public TextHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private TextSortOnClickListener textSortOnClickListener;

    public interface TextSortOnClickListener {
        void onSortClick(View v, int postion);

        void onSortClick(View v, int postion, boolean isFirst);
    }

    public void setOnSortClick(TextSortOnClickListener mOnItemClickLitener) {
        this.textSortOnClickListener = mOnItemClickLitener;
    }

    public class TypetypeHolder extends RecyclerView.ViewHolder {

        public TypetypeHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class TypetypeHolders extends RecyclerView.ViewHolder {
        @Bind(R.id.rv_homepageradapter_artist)
        RecyclerView rvtype;

        public TypetypeHolders(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class NormalHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.tv_title)
        TextView tv_title;

        public NormalHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    @Override
    public int getItemCount() {
        int i = normalGoodsTitls != null ? normalGoodsTitls.size() : 0;
        return count + i + mBottomCount;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.size_flow_layout)
        LinearLayout linearLayout;
        @Bind(R.id.rb)
        RatingBar rb;
        @Bind(R.id.tv_juli_label)
        TextView tv_juli_label;//距离
        @Bind(R.id.tv_orders)
        TextView tv_orders;//销售数量
        @Bind(R.id.tv_avg_score)
        TextView tv_avg_score;//评价
        @Bind(R.id.min_amount)
        TextView min_amount;//起送价
        @Bind(R.id.title)
        TextView title;//商家标题
        @Bind(R.id.draw_goods)
        ImageView draw_goods;//商家头像

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int postion);

        void onItemLongClick(View v, int postion);

    }

    /**
     * 自定义条目点击监听
     */
    private OnItemClickListener mOnItemClickLitener;

    public void setmOnItemClickLitener(OnItemClickListener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }
}

